package com.xzxy.xmlg_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzxy.xmlg_backend.entity.Emp;
import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.entity.dto.EmpDto;
import com.xzxy.xmlg_backend.entity.vo.EmpVo;
import com.xzxy.xmlg_backend.mapper.EmpMapper;
import com.xzxy.xmlg_backend.service.impl.EmpServiceImpl;
import com.xzxy.xmlg_backend.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author 周毅盛
 * @since 2025-06-10
 */
@Slf4j
@RestController
@RequestMapping("/emps")
@Tag(name = "员工管理")
public class EmpController {

    @Autowired
    private EmpServiceImpl empService;

    @Autowired
    private EmpMapper empMapper;

    @PostMapping("/list")
    @Operation(summary = "分页查询",description = "分页查询信息")
    public Result page(@RequestBody EmpDto empDto){
        log.info("分页查询，参数：{}", empDto);
        Page<Emp> page = new Page<>(empDto.getPage(), empDto.getPageSize());
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        if (empDto.getName() != null && !empDto.getName().isEmpty()) {
            wrapper.like(Emp::getName, empDto.getName());
        }
        if (empDto.getGender() != null) {
            wrapper.eq(Emp::getGender, empDto.getGender());
        }
        if (empDto.getBeginTime() != null && empDto.getEndTime() != null) {
            wrapper.between(Emp::getEntrydate, empDto.getBeginTime(), empDto.getEndTime());
        }
        wrapper.orderByDesc(Emp::getUpdateTime);

        empService.page(page, wrapper);

        EmpVo empVo = new EmpVo();
        empVo.setRows(page.getRecords());
        empVo.setTotal(page.getTotal());
        return Result.success(empVo);
    }


    /**
     * 新增员工
     * @param emp
     * @return
     */
    @PostMapping
    @Operation(summary = "新增员工",description = "新增员工信息")
    public Result add(@RequestBody Emp emp){
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        boolean b = empService.save(emp);
        if (b)
            return Result.success();
        return Result.fail("新增员工失败，请稍后再试！");
    }

    /**
     * 修改员工
     * @param emp
     * @return
     */
    @PutMapping
    @Operation(summary = "修改员工",description = "修改员工信息")
    public Result update(@RequestBody Emp emp){
        emp.setUpdateTime(LocalDateTime.now());
        boolean b = empService.updateById(emp);
        if (b)
            return Result.success();
        return Result.fail("修改员工失败，请稍后再试！");
    }


    /**
     * 查询单个员工信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询单个员工",description = "查询单个员工信息")
    public Result getById(@PathVariable Long id){
        return Result.success(empService.getById(id));
    }


    /**
     * 批量删除员工和单个删除员工
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "批量删除员工和单个删除员工",description = "批量删除员工和单个删除员工信息")
    public Result delete(@PathVariable List<Long> ids){
        boolean b = empService.removeByIds(ids);
        if (b)
            return Result.success();
        return Result.fail("批量或者单个删除员工失败，请稍后再试！");
    }

    /**
     * 用户登录
     * @param emp
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "登录接口",description = "用户登录接口")
    public Result login(@RequestBody Emp emp){
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Emp::getUsername,emp.getUsername());
        List<Emp> list = empService.list(wrapper);
        if (list.size() == 0 || list == null)
            return Result.fail("账户不存在!");
        if (! emp.getPassword().equals(list.get(0).getPassword()))
            return Result.fail("账户或密码错误!");
        HashMap map = new HashMap();
        map.put("username",emp.getUsername());
        map.put("id",emp.getId());
        map.put("name",emp.getName());
        map.put("image",emp.getImage());
        String token = JwtUtils.generateJwt(map);
        return Result.success(token);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取员工统计数据", description = "获取员工各项统计信息")
    public Result getEmpStats() {
        // 总员工数
        long totalEmps = empService.count();

        // 按职位统计（过滤掉 job 为 null 的记录）
        List<Emp> allEmps = empService.list();
        Map<Byte, Long> jobCounts = allEmps.stream()
                .filter(emp -> emp.getJob() != null)
                .collect(Collectors.groupingBy(Emp::getJob, Collectors.counting()));

        // 按性别统计（过滤掉 gender 为 null 的记录）
        Map<Byte, Long> genderCounts = allEmps.stream()
                .filter(emp -> emp.getGender() != null)
                .collect(Collectors.groupingBy(Emp::getGender, Collectors.counting()));

        // 按入职年份统计（过滤掉 entrydate 为 null 的记录）
        Map<Integer, Long> yearCounts = allEmps.stream()
                .filter(emp -> emp.getEntrydate() != null)
                .collect(Collectors.groupingBy(
                        emp -> emp.getEntrydate().getYear(),
                        Collectors.counting()
                ));

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalEmps", totalEmps);
        stats.put("jobCounts", jobCounts);
        stats.put("genderCounts", genderCounts);
        stats.put("yearCounts", yearCounts);
        //打印统计结果
        System.out.println(
                "总员工数：" + totalEmps +
                        "\n职位统计：" + jobCounts +
                        "\n性别统计：" + genderCounts +
                        "\n入职年份统计：" + yearCounts
        );
        return Result.success(stats);
    }
}
